package com.atguigu.gmall.order.controller;

import com.atguigu.gmall.cart.client.CartFeignClient;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.order.service.OrderService;
import com.atguigu.gmall.product.client.ProductFeignClient;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/order")
public class OrderApiController {

    @Autowired
    private CartFeignClient cartFeignClient;

    @Autowired
    private ProductFeignClient productFeignClient;

    @Autowired
    private OrderService orderService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    //  返回值类型：
    @GetMapping("/auth/trade")
    public Result trade(HttpServletRequest request){
        //  获取用户Id
        String userId = AuthContextHolder.getUserId(request);
        //  创建map 集合
        HashMap<String, Object> map = new HashMap<>();

        //  获取订单明细 - 获取选中购物车列表！ order_detail
        List<CartInfo> cartCheckedList = cartFeignClient.getCartCheckedList(userId);
        //  声明一个集合列表
        List<OrderDetail> detailArrayList = new ArrayList<>();
        //  金额 AtomicInteger 原子类：
        AtomicInteger totalNum = new AtomicInteger();
        //  循环遍历，将cartCheckedList 变为 detailArrayList
        if (!CollectionUtils.isEmpty(cartCheckedList)){
            //  获取订单明细集合
            detailArrayList = cartCheckedList.stream().map(cartInfo -> {
                //  创建订单明细对象
                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setSkuId(cartInfo.getSkuId());
                orderDetail.setSkuName(cartInfo.getSkuName());
                orderDetail.setSkuNum(cartInfo.getSkuNum());
                orderDetail.setImgUrl(cartInfo.getImgUrl());
                orderDetail.setOrderPrice(cartInfo.getSkuPrice());
                //  += 总件数
                totalNum.addAndGet(cartInfo.getSkuNum());
                //  返回订单明细对象
                return orderDetail;
            }).collect(Collectors.toList());
            //  存储订单明细集合
            map.put("detailArrayList",detailArrayList);
        }
        //  存储总金额totalAmount
        OrderInfo orderInfo = new OrderInfo();
        //  调用这个方法的前提必须给订单明细赋值
        orderInfo.setOrderDetailList(detailArrayList);
        orderInfo.sumTotalAmount();
        map.put("totalAmount",orderInfo.getTotalAmount());
        //  存储总件数 totalNum
        map.put("totalNum",totalNum);
        //  存储页面要的流水号
        map.put("tradeNo",this.orderService.getTradeNo(userId));
        //  返回数据
        return Result.ok(map);
    }

    //  http://api.gmall.com/api/order/auth/submitOrder?tradeNo=null

    /**
     * 保存订单
     * @param orderInfo
     * @param request
     * @return
     */
    @PostMapping("/auth/submitOrder")
    public Result saveOrderInfo(@RequestBody OrderInfo orderInfo,HttpServletRequest request){
        //  获取用户Id
        String userId = AuthContextHolder.getUserId(request);
        //  赋值用户Id
        orderInfo.setUserId(Long.parseLong(userId));
        //  先获取到页面传递的流水号：
        String tradeNo = request.getParameter("tradeNo");
        //  调用比较方法。
        //  单线程操作，多线程就可能会出现误删锁的问题！lua 脚本
        //        Boolean result = this.orderService.checkTradeNo(userId, tradeNo);
        //        if (!result){
        //            //  给他提示信息；
        //            return Result.fail().message("不能重复提交");
        //        }
        //        //  删除流水号
        //        this.orderService.delTradeNo(userId);
        //  声明一个lua脚本
        String scriptText = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                "then\n" +
                "    return redis.call(\"del\",KEYS[1])\n" +
                "else\n" +
                "    return 0\n" +
                "end";
        //  创建对象
        DefaultRedisScript redisScript = new DefaultRedisScript<>();
        redisScript.setScriptText(scriptText);
        redisScript.setResultType(Long.class);
        //  声明个缓存的key
        String tradeNoKey = "user:"+userId+":tradeNo";
        //  执行lua脚本 键与口令串一致的时候就删除，否则就不删除.
        Long result = (Long) this.redisTemplate.execute(redisScript, Arrays.asList(tradeNoKey), tradeNo);
        //  判断是否删除成功.
        if (result==0){
            //  删除失败;
            return Result.fail().message("不能重复提交");
        }

        //  创建多线程集合对象
        List<CompletableFuture> completableFutureArrayList = new ArrayList<>();
        //  存储错误信息集合
        ArrayList<String> errorList = new ArrayList<>();
        //  校验库存： http://localhost:9001/hasStock?skuId=10221&num=2 0：无库存   1：有库存
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        //  遍历整个订单集合
        if (!CollectionUtils.isEmpty(orderDetailList)){
            for (OrderDetail orderDetail : orderDetailList) {
                //  校验库存
                CompletableFuture<Void> stockCompletableFuture = CompletableFuture.runAsync(() -> {
                    //  调用服务层方法。
                    Boolean exist = this.orderService.checkStock(orderDetail.getSkuId(), orderDetail.getSkuNum());
                    //  判断
                    if (!exist) {
                        //return Result.fail().message(orderDetail.getSkuId()+"库存不足!");
                        errorList.add(orderDetail.getSkuId() + "库存不足!");
                    }
                }, threadPoolExecutor);

                //  添加到集合中
                completableFutureArrayList.add(stockCompletableFuture);

                //  校验价格
                CompletableFuture<Void> priceCompletableFuture = CompletableFuture.runAsync(() -> {
                    //  获取当前订单价格
                    BigDecimal orderPrice = orderDetail.getOrderPrice();
                    //  获取当前商品最新价格
                    BigDecimal skuPrice = productFeignClient.getSkuPrice(orderDetail.getSkuId());
                    //  价格比较  orderPrice.compareTo(skuPrice) == 1 降价  -1 涨价
                    if (orderPrice.compareTo(skuPrice) != 0) {
                        //  知道谁变动了！
                        Long skuId = orderDetail.getSkuId();
                        //  购物车的key
                        String cartKey = RedisConst.USER_KEY_PREFIX + userId + RedisConst.USER_CART_KEY_SUFFIX;
                        //  获取当前这个购物项； hget key field;
                        CartInfo cartInfo = (CartInfo) this.redisTemplate.opsForHash().get(cartKey, skuId.toString());
                        cartInfo.setSkuPrice(skuPrice);
                        //  将最新数据写回购物车 hset key field value;
                        this.redisTemplate.opsForHash().put(cartKey, skuId.toString(), cartInfo);
                        //  价格有变动：
                        String msg = orderPrice.compareTo(skuPrice) == 1 ? "降价" : "涨价";
                        //  获取价格变动差额
                        BigDecimal price = orderPrice.subtract(skuPrice).abs();
                        //  返回信息提示
                        errorList.add(orderDetail.getSkuId() + "价格有变动," + msg + price + "元");
                    }
                }, threadPoolExecutor);
                //  将验证价格线程添加到集合中
                completableFutureArrayList.add(priceCompletableFuture);
            }
        }
        //  多线程组合
        CompletableFuture.allOf(completableFutureArrayList.toArray(new CompletableFuture[completableFutureArrayList.size()])).join();
        //  判断是否有错误信息
        if (errorList.size()>0){
            //  返回信息提示
            return Result.fail().message(StringUtils.join(errorList,","));
        }
        //  调用服务层方法
        Long orderId = this.orderService.saveOrderInfo(orderInfo);
        //  返回订单Id
        return Result.ok(orderId);
    }

    /**
     * 查看我的订单 http://139.198.104.58:8200/api/order/auth/1/10?orderStatus=UNPAID
     * @param page
     * @param limit
     * @param request
     * @return
     */
    @GetMapping("/auth/{page}/{limit}")
    public Result myOrder(@PathVariable Long page,
                          @PathVariable Long limit,
                          HttpServletRequest request){
        //  获取到用户Id
        String userId = AuthContextHolder.getUserId(request);
        //  获取到订单的状态
        String orderStatus = request.getParameter("orderStatus");
        //  这是分页查询
        Page<OrderInfo> orderInfoPage = new Page<>(page,limit);
        //  调用服务层方法，返回Ipage对象
        IPage<OrderInfo> iPage = this.orderService.getMyOrder(orderInfoPage,userId,orderStatus);
        //  返回数据
        return Result.ok(iPage);
    }

    /**
     * 根据订单Id 获取订单对象
     * @param orderId
     * @return
     */
    @GetMapping("inner/getOrderInfo/{orderId}")
    public OrderInfo getOrderInfo(@PathVariable Long orderId){
        //  调用服务层方法 获取orderInfo + orderDetail
        return this.orderService.getOrderInfo(orderId);
        //  暂时先不用！
        //  return this.orderService.getById(orderId);
    }

    /**
     * 拆单 http://localhost:8204/api/order/orderSplit?orderId=xxx&wareSkuMap=xxx
     * @param request
     * @return
     */
    @PostMapping("/orderSplit")
    public List<Map<String, Object>> orderSplit(HttpServletRequest request){
        //  获取参数
        String orderId = request.getParameter("orderId");
        //  [{"wareId":"1","skuIds":["22"]},{"wareId":"2","skuIds":["23",,"24"]}]
        String wareSkuMap = request.getParameter("wareSkuMap");
        //  调用服务层方法. 获取 OrderInfo 够成的子订单
        List<OrderInfo> orderInfoList = this.orderService.orderSplit(orderId,wareSkuMap);
        //  改造成我们需要的数据 获取 map 够成的子订单
        List<Map<String, Object>> mapList = orderInfoList.stream().map(orderInfo -> {
            //  将orderInfo 转换为map 集合
            Map<String, Object> map = orderService.initWare(orderInfo);
            return map;
        }).collect(Collectors.toList());
        //  真正的子订单集合
        return mapList;
    }

    /**
     * 保存秒杀订单
     * @param orderInfo
     * @return
     */
    @PostMapping("/inner/seckill/submitOrder")
    public Long submitOrder(@RequestBody OrderInfo orderInfo){
        //  调用服务层方法
        Long orderId = this.orderService.saveOrderInfo(orderInfo);
        return orderId;
    }

}
